package com.gl.codewar.template;

public class ProvideJustification {

	static int max_length = 30;
	
	public static String justify(String sampleInput) {
		
		String ca[] = sampleInput.split(" ");
		
		String cadena_final = "";
		
		int accLinea = 0;
		
		//ordenar lineas
		for (int i = 0; i < ca.length; i++) {
			
			if( accLinea + (ca[i].length()) <= max_length ){
				if(accLinea!=0) cadena_final += "."; 
				cadena_final += ca[i];
				accLinea += ca[i].length() + 1;
			}else{
				cadena_final += "\n";
				accLinea = 0;
				if(accLinea!=0) cadena_final += ".";
				cadena_final += ca[i];
				accLinea += ("."+ca[i]).length();
			}			
		}
		
		return fixJustify(cadena_final);
	}
	
	/*
	 * 
	 
	  String expectedString = "If...Java...had..true..garbage\n" + 
    							"collection.most.programs.would\n" +
    							"delete.....themselves.....upon\n" + 
    							"execution";
	  
	 * 
	 */
	
	private static String fixJustify( String cadena ){
		String fixed = "";
		
		String lineas[] = cadena.split("\n");
		
		for (String linea : lineas) {
			if( linea.length() < max_length ){
				fixed += fixLinea(linea,".") + "\n";	
			}else{
				fixed += linea + "\n";
			}
		}
		
		return fixed.substring(0, fixed.length() - 1); 
	}
	
	private static String fixLinea( String toFix, String split ){
		String linea = "";
		
		if( toFix.length() >= max_length ) return toFix;
		
		String partes[] = toFix.split("\\" + split);
		
		if( partes.length == 1  ) {
			return partes[0];
		}
		
		int ll = 0;
		
		for (int i = 0; i < partes.length; i++) {
			ll += partes[i].length();
		}
		
		int i = 0;
		
		for (i = 0; i < partes.length - 1; i++) {
			
			if( max_length >= ll + ( ( (partes.length - 1) * split.length() ) + 1) ){
				linea += partes[i];
				linea += split + ".";
			}else{
				linea += ( partes[i] + split );
			}
		}
		
		linea += ( partes[i] );
		
		if( linea.length() < max_length ){
			return fixLinea(linea,split+".");
		}else{
			return linea;
		}
	}
}